package org.example.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CollectionUtils {

    @Autowired
    ObjectMapper objectMapper;

    public <T> T convertObject(Object source, Class<T> targetClass) throws JsonProcessingException {
        String json = objectMapper.writeValueAsString(source);
        return objectMapper.readValue(json, targetClass);
    }

    /**
     * 对象转换
     *
     * @param source
     * @param targetType
     * @param <T>
     * @return
     * @throws JsonProcessingException
     */
    public <T> T convertObject(Object source, TypeReference<T> targetType) throws JsonProcessingException {
        String json = objectMapper.writeValueAsString(source);
        return objectMapper.readValue(json, targetType);
    }

}
